<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="商家账号" prop="busName">
      <el-input v-model="ruleForm.busName"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="busPassword">
      <el-input v-model="ruleForm.busPassword" type="password" :disabled="formType == 'update'"></el-input>
    </el-form-item>
    <el-form-item label="商家昵称" prop="nickName">
      <el-input v-model="ruleForm.nickName"></el-input>
    </el-form-item>
    <el-form-item label="手机号码" prop="phone">
      <el-input v-model="ruleForm.phone"></el-input>
    </el-form-item>
    <el-form-item label="性别" prop="sex">
      <el-radio-group v-model="ruleForm.sex">
        <el-radio label="1">男</el-radio>
        <el-radio label="2">女</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="状态" prop="rowState">
      <el-radio-group v-model="ruleForm.rowState">
        <el-radio label="1">启用</el-radio>
        <el-radio label="0">禁用</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="区域" prop="cityId" style="width: 100%">
      <el-cascader
        placeholder="请选择"
        :options="options"
        filterable
        @active-item-change="handleItemChange"
        v-model="ruleForm.cityId"
        clearable
        :props="props"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="formType==='update'?updateForm('ruleForm'):submitForm('ruleForm')"
                 :loading="submitStatus">确定
      </el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
  import * as types from '../../store/mutations-type'
  import api from '../../store/api'
  var format = require('../../util/util')
  import axios from 'axios'
  export default {
    data () {
      var validateCityId = (rule, value, callback) => {
        if (value.length < 1) {
          callback(new Error('请选择区域'))
        } else {
          callback()
        }
      }
      return {
        handle: 'add',
        id: '',
        submitStatus: false,
        ruleForm: {
          busName: '',
          busPassword: '',
          nickName: '',
          phone: '',
          sex: '',
          rowState: '1',
          cityId: [],
          cityName: ''
        },
        flag: {
          a: '',
          b: ''
        },
        rules: {
          busName: [
            {required: true, message: '请请输入商家账号', trigger: 'blur'},
            {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'},
            {pattern: /^(([^^<>%&',;=?$"':#!~\][{}\\/`|])*)$/, message: '不能输入特殊字符'}
          ],
          busPassword: [
            {required: true, message: '请输入密码', trigger: 'blur'},
            {pattern: /^(([^^<>%&',;=?$"':#!~\][{}\\/`|])*)$/, message: '不能输入特殊字符'}
          ],
          nickName: [
            {required: true, message: '请输入商家名称', trigger: 'blur'},
            {message: '长度在 2 到 4 个字符', trigger: 'blur'},
            {pattern: /^(([^^<>%&',;=?$"':#!~\][{}\\/`|])*)$/, message: '不能输入特殊字符'}
          ],
          phone: [
            {required: true, message: '请输入手机号码', trigger: 'blur'},
            {min: 7, max: 12, message: '长度在 6 到 16 个字符', trigger: 'blur'},
            {pattern: /^(13[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/, message: '请输入正确的手机号码'}
          ],
          sex: [
            {message: '请选择性别', trigger: 'blur'}
          ],
          rowState: [
            {required: true, message: '请选择状态', trigger: 'change'}
          ],
          cityId: [
            {required: true, validator: validateCityId, trigger: 'blur'}
          ]
        },
        options: [{
          value: '28',
          label: '甘肃'
        }],
        props: {
          value: 'id',
          label: 'cityName'
        }
      }
    },
    props: ['_ruleForm', 'formType', 'getTableData'],
    methods: {
      handleItemChange (val) {
        var len = val.length - 1
        if (val.length === 1) {
          this.options.map((item, index) => {
            if (item.id === val[len]) {
              this.flag.a = index
              return
            }
          })
          this.getCityLib(val[len])
            .then(result => {
              this.options[this.flag.a].children = result
            })
        }
      },
      getCityLib (id) {
        let url = api.cityLib
        url = id ? url + '?parentId=' + id : url
        return new Promise((resolve, reject) => {
          axios.get(url)
            .then(response => {
              const result = response.data
              if (result.success) {
                resolve(result.data)
              } else {
                reject(result)
              }
            })
        })
      },
      submitForm (formName) {
        this.submitStatus = true
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var ruleForm = this.ruleForm
            ruleForm.cityId = ruleForm.cityId[1]
            ruleForm = format.formatString(ruleForm)
            axios.post(api.supplierAdd, ruleForm).then(response => {
              var result = response.data
              if (result.success) {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                this.submitStatus = false
                this.$store.dispatch(types.SUPPLIER_CLOSE_FORM)
                this.resetForm(formName)
              } else {
                this.submitStatus = false
                this.$message.error({
                  title: '错误',
                  message: result.message
                })
              }
              this.getTableData()
            }, (err) => {
              this.$message.error({
                title: '错误',
                message: err.response.data.message
              })
              this.submitStatus = false
            })
          } else {
            this.submitStatus = false
            console.log('error submit!!')
            return false
          }
        })
      },
      updateForm (formName) {
        this.submitStatus = true
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var ruleForm = this.ruleForm
            ruleForm.cityId = ruleForm.cityId[1]
            delete this.ruleForm.busPassword
            ruleForm = format.formatString(ruleForm)
            axios.put(api.supplierUpdate + '?' + ruleForm).then(response => {
              var result = response.data
              if (result.success) {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                })
                this.submitStatus = false
                this.$store.dispatch(types.SUPPLIER_CLOSE_FORM)
                this.resetForm(formName)
              } else {
                this.submitStatus = false
                this.$message.error({
                  title: '错误',
                  message: result.message
                })
              }
              this.getTableData()
            }, (err) => {
              this.$message.error({
                title: '错误',
                message: err.response.data.message
              })
              this.submitStatus = false
            })
          } else {
            this.submitStatus = false
            console.log('error submit!!')
            return false
          }
        })
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      }
    },
    mounted () {
      this.getCityLib()
        .then(result => {
          this.options = result
          if (this.formType === 'update') {
            this.ruleForm = this._ruleForm
            let _cityId = []
            _cityId.push(this.ruleForm.cityId[0])
            this.handleItemChange(_cityId)
          }
        })
    }
  }
</script>
<style>
  .demo-ruleForm {
    width: 440px;
  }
</style>

